<template>
  <div>
    <px-form ref="ruleFormRef" :rules="rules" inline :model="formValue" label-width="100px">
      <px-form-item label="关联PID图" prop="pidUrl">
        <px-input
          v-model="formValue.pidUrl"
          :disabled="type === 'detail'"
          style="width: 600px"
          maxlength="200"
          placeholder="请输入PID图地址"
          clearable
        />
      </px-form-item>
      <px-form-item v-if="type === 'edit'">
        <px-button type="primary" @click="handleSubmit(ruleFormRef)"> 保存 </px-button>
        <px-button @click="resetForm(ruleFormRef)">取消</px-button>
      </px-form-item>
    </px-form>
    <div v-if="isShowPID" class="iframe-content">
      <iframe :src="pidUrl" width="100%" height="100%" frameborder="0" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { savePid } from "@/api/equip/archive";
import { PxMessage } from "px-ui";
import { computed, ref, watchEffect } from "vue";

const ruleFormRef = ref<any>();

const pidUrl = ref("");

const isShowPID = ref(true);

const formValue = ref<Record<string, any>>({});

const emits = defineEmits(["backMainPage", "getEqpDetails"]);

// 父级传过来的值
const props = defineProps(["eqpDetailData", "type", "activeName"]);

const validatePass = (rule: any, value: any, callback: any) => {
  // if (value === "") {
  //   callback(new Error("请输入PID图地址"));
  // } else
  if (value && !value?.includes("/#/openview/")) {
    callback(new Error("请输入正确格式的PID图地址"));
  } else {
    callback();
  }
};

// 表单校验规则
const rules = computed(() => ({
  pidUrl: [
    { validator: validatePass, trigger: "blur" }
    // { required: true, message: "请输入PID图地址", trigger: "blur" }
  ]
}));

watchEffect(async () => {
  if (props.activeName === "pid") {
    formValue.value.pidUrl = props.eqpDetailData.pidUrl;
    pidUrl.value = props.eqpDetailData.pidUrl;
  }
});

const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      isShowPID.value = false;
      const res = await savePid({
        eqpId: props.eqpDetailData.eqpId,
        pidUrl: formValue.value.pidUrl
      });
      if (res) {
        isShowPID.value = true;
        PxMessage.success("PID图修改成功");
        pidUrl.value = formValue.value.pidUrl;
        emits("getEqpDetails");
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: any) => {
  if (!formEl) return;
  formEl.resetFields();
  emits("backMainPage");
};
</script>

<style lang="scss" scoped>
.iframe-content {
  height: calc(100vh - 320px);
}
</style>
